package per.jdz.demo.readlistener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * @author Jdz
 * @date 2025/2/5
 */
@Slf4j
public class WriteListener<T> extends AbstractListener<T> {

    public WriteListener(String outputFileNamePrefix, String outputFileNameSuffix, String splitSavePath) {
        super(outputFileNamePrefix, outputFileNameSuffix, splitSavePath);
    }

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        // 将数据添加到当前批次
//        log.info(data.toString());
        currentBatch.add(data);
        if (currentBatch.size() == BATCH_SIZE) {
            // 写入当前批次的数据到新文件
            writeBatchToFile(currentBatch, fileCounter.getAndIncrement());
            // 清空当前批次
            currentBatch.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 如果还有剩余未写入的数据，则写入最后一批
        if (!currentBatch.isEmpty()) {
            writeBatchToFile(currentBatch, fileCounter.getAndIncrement());
        }
        log.info("{}: 所有数据已处理完毕", outputFileNamePrefix);
    }

    protected void writeBatchToFile(List<T> batch, int partNumber) {
        // 创建输出文件名
        String fileName = outputFileNamePrefix + "-" + partNumber + outputFileNameSuffix;
        // 这里需要根据实际情况指定文件保存路径
        File outFile = new File(splitSavePath + "/" + fileName);
        // 使用EasyExcel将批次数据写入文件
        EasyExcel.write(outFile).sheet().doWrite(batch);
    }

}
